package com.yyhn.guilimall.product.exception;

import com.yyhn.common.exception.BizCodeEnume;
import com.yyhn.common.utils.R;

import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;
/*
*统一异常处理类
* */
@RestControllerAdvice("com.yyhn.guilimall.product.controller")
@Log4j2
public class GuliMallExceptionController {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.info(e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,Object>map=new HashMap<>();
        bindingResult.getFieldErrors().forEach((itme)->{
            map.put(itme.getField(),itme.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(Throwable.class)
    public R handlerException(Throwable throwable){
       return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
